package com.globallogic.jira.gadget.servlet;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.config.ConstantsManager;
import com.atlassian.jira.issue.issuetype.IssueType;
import com.atlassian.jira.issue.link.IssueLinkType;
import com.atlassian.jira.issue.link.IssueLinkTypeManager;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.project.version.Version;
import com.atlassian.templaterenderer.TemplateRenderer;

/**
 * 
 * @author anton.pereverziev
 * 
 */
@SuppressWarnings("serial")
public class ProjectsListBuilder extends HttpServlet {

    private final TemplateRenderer renderer;

    /**
     * Servlet constructor that is auto-wired by Spring to include the following
     * services registered in the params.
     * 
     * @param templateRenderer
     */
    public ProjectsListBuilder(TemplateRenderer templateRenderer) {
	this.renderer = templateRenderer;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {

	String projectName = req.getParameter("projectName");

	Map<String, Object> velocityParams = new HashMap<String, Object>();

	List<Project> allProjects = ComponentManager.getInstance()
		.getProjectManager().getProjectObjects();
	velocityParams.put("projects", allProjects);
	ConstantsManager constantsManager = ComponentManager.getInstance()
		.getConstantsManager();
	Collection<IssueType> issueTypes = constantsManager
		.getAllIssueTypeObjects();
	velocityParams.put("issues", issueTypes);

	IssueLinkTypeManager issueLinkTypeManager = ComponentManager
		.getComponentInstanceOfType(IssueLinkTypeManager.class);

	Collection<IssueLinkType> linkTypes = issueLinkTypeManager
		.getIssueLinkTypes();

	velocityParams.put("linkTypes", linkTypes);
	ProjectManager projectManager = ComponentManager.getInstance()
		.getProjectManager();

	Project project = projectManager.getProjectObjByName(projectName);
	Collection<Version> versions = null;
	if (project != null) {
	    versions = project.getVersions();
	}
	velocityParams.put("versions", versions);
	resp.setContentType("text/html");
	renderer.render("project_select.vm", velocityParams, resp.getWriter());

    }
}
